package users;

import algos.Vocabulary;
import utils.Common;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

import static utils.Common.newHashMap;

public class Users {


    public static final String USER_FOLDER = "users";
    public static final long DUMP_TIMEOUT = 10000;

    private static final int MAX_NGRAM = 3;

    private Users() {
    }


    private static Map<Integer, UserStatistic> statisticUsers = newHashMap();

    private static ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    static {
        executor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    for (Iterator<UserStatistic> iterator = statisticUsers.values().iterator(); iterator.hasNext();) {
                        UserStatistic statistic = iterator.next();
                        if (System.currentTimeMillis() - statistic.lastUsageTimeStamp() > DUMP_TIMEOUT) {
                            iterator.remove();
                            statistic.unload();
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 1, 1, TimeUnit.MINUTES);
    }

    public static UserStatistic getUserStatisticFor(int userId, Vocabulary baseVoc) {
        UserStatistic stat = statisticUsers.get(userId);
        if (stat == null) {
            stat = new UserStatistic(userId, baseVoc);
            statisticUsers.put(userId, stat);
        }
        return stat;
    }

    public static int userMaxNGramLength() {
        return MAX_NGRAM;
    }


}
